<template>
  <div class="py-4">
    <BasicTable :dataSource="props.data" @register="registerTable">
      <template #mg_state="{ record }">
        <a-switch
          v-model:checked="record.mg_state"
          @change="() => handleSwitchChange(record)"
          :loading="record.rowLoading"
          :disabled="!record.editStatus && state.otherDisable"
        />
      </template>
      <template #role_name="{ record }">
        <div v-if="!record.editStatus">
          <span>{{ record.role_name }}</span>
          <a-button
            type="link"
            @click="handleEditRole(record)"
            :disabled="!record.editStatus && state.otherDisable"
          >
            <EditOutlined />
          </a-button>
        </div>
        <div v-else>
          <a-select
            ref="select"
            :value="{ value: state.selectValue }"
            style="width: 120px"
            @select="
              (value) => {
                handleSelect(value, record);
              }
            "
            :disabled="record.rowLoading"
            :labelInValue="true"
          >
            <a-select-option :key="0" :value="0">请选择</a-select-option>
            <a-select-option v-for="item in state.roleData" :key="item.id" :value="item.id">{{
              item.roleName
            }}</a-select-option>
          </a-select>
          <a class="ml-2 text-red-500 hover:text-red-600" @click="handleCancel(record)">
            <CloseCircleFilled />
          </a>
        </div>
      </template>
      <template #operations="{ record }">
        <TableAction
          :actions="[
            {
              label: '删除',
              icon: 'ic:outline-delete-outline',
              // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
              disabled: !record.editStatus && state.otherDisable,
              popConfirm: {
                title: '是否删除？',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
      <template #toolbar>
        <a-button type="primary" @click="emits('openModal')">添加用户</a-button>
        <a-button type="primary" @click="toggleCanResize">{{
          !canResize ? '自适应高度' : '取消自适应'
        }}</a-button>
        <a-button type="primary" @click="toggleBorder">{{
          !border ? '显示边框' : '隐藏边框'
        }}</a-button>
        <a-button type="primary" @click="toggleStriped">{{
          !striped ? '显示斑马纹' : '隐藏斑马纹'
        }}</a-button>
      </template>
    </BasicTable>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted, watch } from 'vue';
  import { useTable, BasicTable, TableAction } from '/@/components/Table';
  import type { BasicColumn } from '/@/components/Table';
  import { useShopUserStore } from '/@/store/modules/shopUsers';
  import { EditOutlined, CloseCircleFilled } from '@ant-design/icons-vue';
  import { useShopRoleStore } from '/@/store/modules/shopRoleStore';
  import { message } from 'ant-design-vue';

  interface stateModel {
    columns: BasicColumn[];
    roleData: Object[] | any;
    selectValue: number;
    otherDisable: boolean;
  }

  const shopUserStore = useShopUserStore();
  const shopRoleStore = useShopRoleStore();
  const props = defineProps({
    data: Array as PropType<Recordable[]>,
    listLoading: Boolean,
  });
  const state: stateModel = reactive({
    columns: [
      {
        title: 'ID',
        dataIndex: 'id',
        fixed: 'left',
        width: 200,
      },
      {
        title: '用户名',
        dataIndex: 'username',
      },
      {
        title: '手机',
        dataIndex: 'mobile',
      },
      {
        title: '邮箱',
        dataIndex: 'email',
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
      },
      {
        title: '状态',
        dataIndex: 'mg_state',
        slots: { customRender: 'mg_state' },
      },
      {
        title: '管理类型',
        dataIndex: 'role_name',
        slots: { customRender: 'role_name' },
      },
    ],
    roleData: [],
    selectValue: 0,
    otherDisable: false,
  });

  const emits = defineEmits(['openModal', 'updateUser', 'deleteUser']);
  const canResize = ref(false);
  const striped = ref(true);
  const border = ref(true);

  const [registerTable] = useTable({
    title: '用户管理',
    titleHelpMessage: 'users',
    columns: state.columns,
    canResize: canResize,
    loading: props.listLoading,
    striped: striped,
    bordered: border,
    showTableSetting: false,
    tableSetting: {
      // 是否显示刷新按钮
      redo: false,
      // 是否显示尺寸调整按钮
      size: false,
      // 是否显示字段调整按钮
      setting: false,
      // 是否显示全屏按钮
      fullScreen: false,
    },
    actionColumn: {
      title: '操作',
      dataIndex: 'operations',
      slots: { customRender: 'operations' },
    },
  });

  // 获取角色权限列表
  async function getRoleList() {
    try {
      const roleList = await shopRoleStore.roleList();
      state.roleData = [...roleList];
    } catch (error) {
      console.log(error);
    }
  }

  function toggleCanResize() {
    canResize.value = !canResize.value;
  }
  function toggleStriped() {
    striped.value = !striped.value;
  }
  function toggleBorder() {
    border.value = !border.value;
  }
  // 修改角色权限
  async function handleSelect(selectRow, record) {
    record.rowLoading = true;
    try {
      await shopUserStore.editUserRole({ id: record.id, rid: selectRow.value });
      message.success('修改成功');
    } catch (error) {
      console.log(error);
    }
    record.role_name = selectRow.label.children;
    record.editStatus = false;
    record.rowLoading = false;
    state.otherDisable = false;
  }
  // 点击编辑角色
  function handleEditRole(record) {
    record.editStatus = true;
    state.otherDisable = true;
    state.roleData.forEach((item) => {
      if (item.roleName == record.role_name) {
        return (state.selectValue = item.id);
      }
    });
  }
  // 取消编辑
  function handleCancel(record: any) {
    record.editStatus = false;
    state.otherDisable = false;
  }
  // 更新用户状态
  function handleSwitchChange(record: any) {
    const { id, mg_state } = record;
    const params = {
      uId: id,
      type: mg_state,
    };
    const value = [params, record];
    emits('updateUser', value);
  }
  // 删除用户
  function handleDelete(record: any) {
    const { id } = record;
    const params = { id };
    const value = [params, record];
    emits('deleteUser', value);
  }

  onMounted(() => {
    props.data?.forEach((item) => {
      item.editStatus = false;
    });
  });

  watch(
    () => props.data,
    () => {
      getRoleList();
    },
  );
</script>
